package controllers

import (
	"net/http"
	"io/ioutil"
	"encoding/json"
	"git.oschina.net/YPTArch/auth/models"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"errors"
)

func Refresh(w http.ResponseWriter, r *http.Request) {
	logs.Logger.Debug("success in refresh")

	var result models.Result
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"刷新token读取请求失败！", Data:""}
	}

	token, err := refreshHandler(data)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"刷新token处理失败！", Data:""}
	}else {
		result = models.Result{Code:models.Ok, Msg:"刷新token成功！", Data:token}
	}

	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)

}


func refreshHandler(data []byte) (refreshToken models.GenerateTokenResponse, err error)   {

	//------解析部分-----
	var generateRefreshToken models.GenerateTokenByRefreshTokenRequest
	err = json.Unmarshal(data, &generateRefreshToken)
	if err != nil {
		logs.Logger.Error("refresh umarshall user err:"+err.Error())
		return
	}

	//如果token不为空，则为刷新token。
	user, err := models.GetUserStruct(REFRESH+generateRefreshToken.RefreshToken)
	if err != nil {
		logs.Logger.Error("refresh GetUserStruct user err:"+err.Error())
		return
	}

	//如果user为空就不操作
	if user.UserId == "" {
		err = errors.New("refresh user is invalidate!")
		return
	}

	refreshToken, err = saveTokenAndRefresh(user, true)
	if err != nil {
		logs.Logger.Error("refresh saveTokenAndRefresh user err:"+err.Error())
		return
	}

	//删除原有token
	_, err = models.Remove(REFRESH+generateRefreshToken.RefreshToken)
	if err != nil {
		logs.Logger.Error("refresh Remove refreshToken err:"+err.Error())
		return
	}

	return

}